package com.gateway.server.common.listener.sys;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.web.context.WebServerInitializedEvent;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationListener;
import org.springframework.stereotype.Service;

import java.net.InetAddress;
import java.net.UnknownHostException;

@Service
public class AppWebServerListener implements ApplicationListener<WebServerInitializedEvent> {

    private final Logger logger = LoggerFactory.getLogger(AppWebServerListener.class);

    private int serverPort;
    private String rootPath;

    public String getUrl() {
        try {
            InetAddress address = InetAddress.getLocalHost();
            return "http://" + address.getHostAddress() + ":" + this.serverPort + this.rootPath;
        } catch (UnknownHostException e) {
            e.printStackTrace();
        }
        return null;
    }

    public String getHost() {
        try {
            InetAddress address = InetAddress.getLocalHost();
            return address.getHostAddress();
        } catch (UnknownHostException e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 实现EnvironmentAware接口，初始化系统数据。
     */
    @Override
    public void onApplicationEvent(WebServerInitializedEvent event) {
        ApplicationContext applicationContext = event.getApplicationContext();
        serverPort = event.getWebServer().getPort();
        rootPath = applicationContext.getApplicationName();
        String appName = applicationContext.getApplicationName();
        logger.info("系统[{}]路径[{}]", appName, getUrl());
    }
}
